package com.mobiusws.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.springframework.stereotype.Component;

import com.mobiusws.reports.action.DailyFraudSummaryAction;

@Component("jsonUtil")
public class JsonUtil {
	private JsonConfig dateConfig;
	private JsonConfig timeConfig;

	public JsonUtil() {
		this.dateConfig = new JsonConfig();
		dateConfig.registerJsonValueProcessor(Date.class,
				new JsonValueProcessor() {

					private SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd");

					@Override
					public Object processObjectValue(String key, Object value,
							JsonConfig cfg) {
						return dateFormat.format((Date) value);
					}

					@Override
					public Object processArrayValue(Object value, JsonConfig cfg) {
						return dateFormat.format((Date) value);
					}
				});
		this.timeConfig = new JsonConfig();
		timeConfig.registerJsonValueProcessor(Date.class,
				new JsonValueProcessor() {

					private SimpleDateFormat timeConfig = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");

					@Override
					public Object processObjectValue(String key, Object value,
							JsonConfig cfg) {
						return timeConfig.format((Date) value);
					}

					@Override
					public Object processArrayValue(Object value, JsonConfig cfg) {
						return timeConfig.format((Date) value);
					}
				});
	}

	private JsonConfig getConfig(boolean isTime) {
		return (isTime ? timeConfig : dateConfig);
	}

	public String getJsonByList(List<?> list, int total, boolean isTime) {
		StringBuilder jsonBld=new StringBuilder();
		JsonConfig config = getConfig(isTime);
		String root=JSONArray.fromObject(list, config).toString();
		jsonBld.append("{\"total\":").append(total).append(",\"root\":").append(root).append("}");
		return jsonBld.toString();
	}

	public String getJsonByObject(Object obj, boolean isTime) {
		JsonConfig config = getConfig(isTime);
		return JSONObject.fromObject(obj, config).toString();
	}

	public String getJsonByList(List<?> list, int total) {
		// get date config by default
		return getJsonByList(list, total, false);
	}

	public String getJsonByObject(Object obj) {
		// get date config by default
		return getJsonByObject(obj, false);
	}

}
